#include "screen.h"
#include "util/screen_util.h"

Screen::Screen()
    : tft(TFT_eSPI()) {
    imageBuffer = new uint8_t[IMAGE_SIZE + 3]; // 堆分配缓冲区
    memset(imageBuffer, 0, IMAGE_SIZE + 3);
}

Screen::~Screen() {
    delete[] imageBuffer;
}

void Screen::setup() {
    tft.init();
    tft.setRotation(2);
    tft.setSwapBytes(true);
    tft.invertDisplay(true);
    tft.fillScreen(TFT_BLACK);
}

void Screen::showStartupMessage(const String &msg) {
    ScreenUtil::showStartupMessage(tft, msg);
}

void Screen::displayFullImage(WiFiClient &client) {
    size_t received = 0;

    // 阻塞接收整张图
    while (received < IMAGE_SIZE + 3) {
        if (client.available()) {
            int r = client.read(imageBuffer + received, IMAGE_SIZE + 3 - received);
            if (r > 0) received += r;
        }
        delay(1); // 防止阻塞太紧
    }

    // 校验尾部
    if (imageBuffer[IMAGE_SIZE] != TAIL_BYTE_1 ||
        imageBuffer[IMAGE_SIZE + 1] != TAIL_BYTE_2 ||
        imageBuffer[IMAGE_SIZE + 2] != TAIL_BYTE_3) {
        client.write("error");
        return;
        }

    // 显示整张图
    tft.fillScreen(TFT_BLACK);
    tft.pushImage(0, 0, WIDTH, HEIGHT, (uint16_t*)imageBuffer);

    client.write("ok");
}